﻿$currentScriptPath = Split-Path -Parent $MyInvocation.MyCommand.Path

# 定义配置文件路径
$migratorConfigFilePath = Join-Path -Path $currentScriptPath -ChildPath "migrator.json"

# 加载配置文件
if (Test-Path $migratorConfigFilePath) {
    $config = Get-Content -Path $migratorConfigFilePath | ConvertFrom-Json
} else {
    # 默认配置
    $config = @{
        MigrationDownloadUrl = ""
        MigrationDllName = ""
        DeploymentEnvironment = "Production"  # 默认环境为生产
    }
}

$downloadDirectory = Join-Path -Path $currentScriptPath -ChildPath "download"
$migratorDirectory = Join-Path -Path $currentScriptPath -ChildPath "migrator"
$zipFileName = [System.IO.Path]::GetFileName($config.MigrationDownloadUrl)
$zipFilePath = Join-Path -Path $downloadDirectory -ChildPath $zipFileName

# 循环执行操作
while ($true) {
    do {
        $Action = Read-Host "请输入操作 (config/do/update/exit)"
    } while ("config", "do", "update", "exit" -notcontains $Action)

    switch ($Action) {
        "config" {
            Write-Output "当前配置："
            Write-Output "迁移包下载地址: $($config.MigrationDownloadUrl)"
            Write-Output "迁移dll名称: $($config.MigrationDllName)"
            Write-Output "部署环境: $($config.DeploymentEnvironment)"

            # 是否修改配置
            $modifyConfig = Read-Host "是否要修改配置? (y/n)"
            if ($modifyConfig -eq 'y') {
                # 修改迁移包下载地址
                $newDownloadUrl = Read-Host "请输入新的迁移包下载地址 (当前: $($config.MigrationDownloadUrl))"
                if (![string]::IsNullOrWhiteSpace($newDownloadUrl)) {
                    $config.MigrationDownloadUrl = $newDownloadUrl
                }

                # 修改迁移 DLL 名称
                $newDllName = Read-Host "请输入新的迁移 DLL 名称 (当前: $($config.MigrationDllName))"
                if (![string]::IsNullOrWhiteSpace($newDllName)) {
                    $config.MigrationDllName = $newDllName
                }

                # 修改部署环境
                $newEnvironment = Read-Host "请输入新的部署环境 (当前: $($config.DeploymentEnvironment))"
                if (![string]::IsNullOrWhiteSpace($newEnvironment)) {
                    $config.DeploymentEnvironment = $newEnvironment
                }

                # 保存配置文件
                Write-Output "正在保存新的配置..."
                if ($PSVersionTable.PSVersion.Major -ge 6) {
                    ConvertTo-Json -InputObject $config | Out-File -FilePath $migratorConfigFilePath -Encoding utf8BOM
                } else {
                    $jsonContent = ConvertTo-Json -InputObject $config
                    $bom = [byte[]]@(0xEF, 0xBB, 0xBF)
                    $bytes = [System.Text.Encoding]::UTF8.GetBytes($jsonContent)
                    [System.IO.File]::WriteAllBytes($migratorConfigFilePath, $bom + $bytes)
                }
                Write-Output "配置已更新。"
            }
            break
        }
        "do" {
            # 直接执行迁移逻辑
            Write-Output "执行迁移操作..."

            # 检查是否有本地zip包，否则远程下载并解压迁移包
            if (Test-Path $zipFilePath) {
                Write-Output "找到本地迁移包，正在解压..."
                Expand-Archive -Path $zipFilePath -DestinationPath $migratorDirectory -Force
                Write-Output "迁移包已成功解压到 $migratorDirectory"
            } else {
                Write-Output "迁移包目录不存在，正在下载迁移包..."
                Invoke-WebRequest -Uri $config.MigrationDownloadUrl -OutFile $zipFilePath
                Expand-Archive -Path $zipFilePath -DestinationPath $migratorDirectory -Force
                Write-Output "迁移包已成功解压到 $migratorDirectory"
            }

            # 切换到解压的目录
            Set-Location -Path $migratorDirectory

            # 使用 dotnet 运行迁移，带上 --environment 参数
            $migrationDllPath = Join-Path -Path $migratorDirectory -ChildPath $config.MigrationDllName

            Write-Output "正在执行数据库迁移... 环境：$($config.DeploymentEnvironment)"

            # 构建 dotnet 命令，传入 --environment 参数
            & dotnet $migrationDllPath --environment $config.DeploymentEnvironment

            if ($LASTEXITCODE -eq 0) {
                Write-Output "数据库迁移成功。"
            } else {
                Write-Output "数据库迁移失败。"
            }

            # 返回原始工作目录
            Set-Location -Path $currentScriptPath
            break
        }
        "update" {
            # 重新下载迁移包并执行迁移
            Write-Output "正在重新下载迁移包并执行迁移..."
            
            # 删除旧的迁移包文件
            if (Test-Path $zipFilePath) {
                Remove-Item $zipFilePath -Force
                Write-Output "旧的迁移包已被删除。"
            }

            # 重新下载迁移包
            Invoke-WebRequest -Uri $config.MigrationDownloadUrl -OutFile $zipFilePath
            Write-Output "迁移包已重新下载到 $zipFilePath"

            # 解压迁移包
            Expand-Archive -Path $zipFilePath -DestinationPath $migratorDirectory -Force
            Write-Output "迁移包已成功解压到 $migratorDirectory"

            # 切换到解压的目录
            Set-Location -Path $migratorDirectory

            # 使用 dotnet 运行迁移，带上 --environment 参数
            $migrationDllPath = Join-Path -Path $migratorDirectory -ChildPath $config.MigrationDllName

            Write-Output "正在执行数据库迁移... 环境：$($config.DeploymentEnvironment)"

            # 构建 dotnet 命令，传入 --environment 参数
            & dotnet $migrationDllPath --environment $config.DeploymentEnvironment

            if ($LASTEXITCODE -eq 0) {
                Write-Output "数据库迁移成功。"
            } else {
                Write-Output "数据库迁移失败。"
            }

            # 返回原始工作目录
            Set-Location -Path $currentScriptPath
            break
        }
        "exit" {
            Write-Output "退出脚本。"
            exit 0
        }
    }
}
